//
//  SYDetailDynamicViewController.m
//  ChatDemo-UI2.0
//
//  Created by zz on 17/3/3.
//  Copyright © 2017年 zz. All rights reserved.
//

#import "SYDetailDynamicViewController.h"
#import "SYNewDynamicViewController.h"
@interface SYDetailDynamicViewController ()<UITableViewDelegate,UITableViewDataSource,LikeCommentViewDelegate,UITextViewDelegate,UIActionSheetDelegate>

@property (nonatomic,strong) UITableView *table;

@property (nonatomic,strong) NSDictionary *dict;

//用于view的移动，使评论框落在cell下面
@property (nonatomic,assign)float replyViewDraw;

@property (nonatomic,strong) UIView *backView;

//表情页面
@property(nonatomic,strong) UIButton *emotionButton;
@property(nonatomic,strong)UITextView *textView;
@property(nonatomic,strong) UIView *bottomView;


@end

@implementation SYDetailDynamicViewController{
    
    BOOL  isZhan;
    UIButton *zanBtn;
    UIButton *pingBtn;
    UIButton *cangBtn;

    UITapGestureRecognizer *dismissTap;
    
    UIImageView *img;
    UIControl *control;

}

#pragma mark -Getter
- (UITableView *)table{
    
    if (!_table) {
        
        _table = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, VIEW_WIDTH, VIEW_HEIGHT - SafeAreaTopHeight) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        _table.tableFooterView = [[UIView alloc] init];
        _table.showsVerticalScrollIndicator = NO;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
        dismissTap = tap;
        dismissTap.enabled = NO;
        [_table addGestureRecognizer:tap];
    }
    
    return _table;
}

#pragma mark -LifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navBar.nav_titleLabel.text= @"详情";
    
    [self requestForDeatilDynamic];
    [self.view addSubview:self.table];
    
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREENHEIGH, SCREENWIDTH, 50)];
    _bottomView.backgroundColor = RGBACOLOR(247, 247, 247, 1);
    
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 10, SCREENWIDTH-40, 30)];
    
    _textView.textColor = [UIColor blackColor];
    
    _textView.layer.masksToBounds = YES;
    //_textView.layer.borderWidth = 0.6;
    
    _textView.returnKeyType = UIReturnKeySend;
    _textView.font = [UIFont systemFontOfSize:14];
    _textView.delegate = self;
    _textView.scrollEnabled = YES;
    //[_textView becomeFirstResponder];
    
    //显示右侧的指示
    _textView.showsVerticalScrollIndicator = YES;
    //这句话可以让textview输入中文的时候不在上下跳动
    _textView.layoutManager.allowsNonContiguousLayout = NO;
    [_bottomView addSubview:_textView];
    
    [self configureKeyboardNoti];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    [_textView resignFirstResponder];
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}





#pragma mark -注册键盘通知
- (void)configureKeyboardNoti{
    
    //    注册键盘消息通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboradWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}

//keyboard显示
- (void)keyboradWillShow:(NSNotification *)note{

    NSDictionary *dict = note.userInfo;
    CGSize keyboardSize = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    CGFloat offY = SCREENHEIGH - keyboardSize.height - _bottomView.frame.size.height;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    _bottomView.frame = CGRectMake(0, offY, VIEW_WIDTH, 50);
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)note{
    
    [UIView beginAnimations:nil context:NULL];
    
    [UIView setAnimationDuration:0.3];
    
    _bottomView.frame = CGRectMake(0, SCREENHEIGH + 50, SCREENWIDTH, 50);
    [UIView commitAnimations];
}


#pragma mark -UITableViewDelegate && UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dict ? 1 : 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellID = @"cellid";
    FriendDynamicViewCell *cell = [[FriendDynamicViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    
    [cell.deleteBtn addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchUpInside];
    
    [cell.clickBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [cell upDateCellWithDic:_dict];
    
    //设置头像
    NSString *logoStr = [_dict objectForKey:@"logo"];
    
    if (![logoStr hasPrefix:@"http"]) {
        logoStr = [REQUESTIMAGEURL stringByAppendingString:logoStr];
    }
    
    [cell.headImage.headImage sd_setImageWithURL:[NSURL URLWithString:logoStr] placeholderImage:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.likeCommentView.delegate = self;
    cell.likeCommentView.tag = indexPath.row;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat imagesHeight;  //图片占有高度
    CGFloat comHeight; //回复view的高度
    CGFloat contentHeight;  //内容高度
    
    
    DFBaseLineItem *item = [DFBaseLineItem dictionaryWithDic:_dict];
    
    if (!(item.praiseuser.count == 0 && item.replylist.count == 0)) {
        
        comHeight=[replayView getHeight:item maxWidth:SCREENWIDTH- 89];
    }
    
    NSString * fileidsStr = [_dict objectForKey:@"fileid"];
    
    NSInteger line = 0;
    
    NSArray *fileids;
    
    if (fileidsStr.length != 0) {
        
        fileids = [fileidsStr componentsSeparatedByString:@","];
    }
    
    
    if ([fileids count]%3 == 0) {
        line = [fileids count]/3;
    }else
    {
        line = [fileids count]/3 + 1;
    }
    
    if (line > 0) {
        
        imagesHeight = 79 + (79 + 5) * (line - 1);
    }else{
        
        imagesHeight = -10;
    }
    
    contentHeight = [self resizeContenLabelHeightWithSting:[_dict objectForKey:@"scontent"]];
    //            contentHeight += 8  //加上边距
    
    return   36 + imagesHeight + contentHeight + comHeight + 32 + 8 + 15;
    

}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    
//    if ([_textView isFirstResponder]) {
//        
//        [_textView resignFirstResponder];
//    }
//}

#pragma mark -- other
- (CGFloat)resizeContenLabelHeightWithSting:(NSString *)text
{
    if (text.length == 0) {
        return 0;
    }
    UIFont *font = [UIFont systemFontOfSize:14];
    
    NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin/* |
                                                                        NSStringDrawingUsesFontLeading*/;
    
    //NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    //[style setLineBreakMode:NSLineBreakByCharWrapping];
    
    NSDictionary *attributes = @{ NSFontAttributeName : font/*, NSParagraphStyleAttributeName : style*/ };
    
    CGSize maxSize = CGSizeMake(SCREENWIDTH - 11 - 64, CGFLOAT_MAX);
    CGSize size = [text boundingRectWithSize:maxSize
                                     options:opts
                                  attributes:attributes
                                     context:nil].size;
    return size.height;
}


#pragma mark -Action

- (void)tapAction{
    
    if ([_textView isFirstResponder]) {
        
        [_textView resignFirstResponder];
        
    }
    if (_backView.hidden == NO) {
        
        _backView.hidden = YES;
    }
    
    dismissTap.enabled = NO;
}


//删除
- (void)deleteAction{
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"删除" otherButtonTitles: nil];
    sheet.tag = 100; //删除的是此条动态
    [sheet showInView:self.view];
}

- (void)clickAction:(UIButton *)sender{

    //因为交互按钮已经弹出来，所以开启tap事件，来响应是否隐藏这个按钮，如果这个按钮隐藏的时候就关闭这个tap事件，以免影响回复事件
    dismissTap.enabled = YES;
    
    NSString *stateZan=[_dict objectForKey:@"ispraise"];//ispraise 点赞、取消状态值
    NSString *infoid=[_dict objectForKey:@"infoid"];//动态id
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    FriendDynamicViewCell *cell=[self.table cellForRowAtIndexPath:indexPath];//获取当前点击cell
    
    self.replyViewDraw = [cell convertRect:cell.bounds toView:self.view.window].origin.y + cell.frame.size.height;
    
    [_backView removeFromSuperview];
    _backView=[[UIView alloc]initWithFrame:CGRectMake(sender.frame.origin.x- 145, sender.frame.origin.y - 22, 180, 30)];
    _backView.centerY = sender.centerY - 9;
    _backView.layer.cornerRadius=5;
    _backView.backgroundColor= [UIColor colorWithHexString:@"#1ebfff"];
    [cell addSubview:_backView];
    
    zanBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    zanBtn.frame=CGRectMake(0, 0, 60, 30);
    [zanBtn setImage:[UIImage imageNamed:@"dianzan_nor"] forState:UIControlStateNormal];
    [zanBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 6.5, 0, 0)];
    zanBtn.tag=[infoid intValue];
    if ([stateZan intValue]==0) {
        [zanBtn setTitle:@"点赞" forState:UIControlStateNormal];
        [zanBtn addTarget:self action:@selector(zanTouchAction:) forControlEvents:UIControlEventTouchUpInside];
    }else
    {
        [zanBtn setTitle:@"取消" forState:UIControlStateNormal];
        [zanBtn addTarget:self action:@selector(qxzanTouchAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    zanBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
    zanBtn.titleLabel.font=[UIFont systemFontOfSize:14];
    [zanBtn setTitleEdgeInsets:UIEdgeInsetsMake(0,10.5,0,0)];
    
    [_backView addSubview:zanBtn];
    
    UIView *line01=[[UIView alloc]initWithFrame:CGRectMake(60, 5, 0.5, 20)];
    line01.backgroundColor=[UIColor whiteColor];
    [_backView addSubview:line01];
    
    pingBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    pingBtn.frame=CGRectMake(60, 0, 60, 30);
    pingBtn.tag=[infoid intValue];
    [pingBtn setImage:[UIImage imageNamed:@"pinglun_nor"] forState:UIControlStateNormal];
    [pingBtn setImageEdgeInsets:UIEdgeInsetsMake(0,-3,0,0)];
    
    [pingBtn setTitle:@"评论" forState:UIControlStateNormal];
    pingBtn.titleLabel.font=[UIFont systemFontOfSize:14];
    [pingBtn setTitleEdgeInsets:UIEdgeInsetsMake(0,5.5,0,0)];
    [pingBtn addTarget:self action:@selector(pingTouchAction:) forControlEvents:UIControlEventTouchUpInside];
    [_backView addSubview:pingBtn];
    
    UIView *line02=[[UIView alloc]initWithFrame:CGRectMake(120, 5, 0.5, 20)];
    line02.backgroundColor=[UIColor whiteColor];
    [_backView addSubview:line02];
    
    cangBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    cangBtn.frame=CGRectMake(120, 0, 60, 30);
    cangBtn.tag=[infoid intValue];
    [cangBtn setImage:[UIImage imageNamed:@"shoucang_nor"] forState:UIControlStateNormal];
    [cangBtn setImageEdgeInsets:UIEdgeInsetsMake(0,-4.5,0,0)];
    [cangBtn setTitle:@"收藏" forState:UIControlStateNormal];
    cangBtn.titleLabel.font=[UIFont systemFontOfSize:14];
    [cangBtn setTitleEdgeInsets:UIEdgeInsetsMake(0,2.5,0,0)];
    [cangBtn addTarget:self action:@selector(cangAction:) forControlEvents:UIControlEventTouchUpInside];
    [_backView addSubview:cangBtn];

}

//点赞响应事件
-(void)zanTouchAction:(UIButton *)sender
{
    [_backView removeFromSuperview];
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_info_praiseadd" forKey:@"method"];
    [dict setObject:_infoid forKey:@"infoid"];
    [dict setObject:USERID forKey:@"userid"];
    
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        
        [self requestForDeatilDynamic];
        
    } failure:^(NSInteger recode, NSError * error){
        
    }];
}
//取消点赞响应事件
-(void)qxzanTouchAction:(UIButton *)sender
{
    [_backView removeFromSuperview];
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_info_praisedel" forKey:@"method"];
    [dict setObject:_infoid forKey:@"infoid"];
    [dict setObject:USERID forKey:@"userid"];
    
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        
        [self requestForDeatilDynamic];
        
    } failure:^(NSInteger recode, NSError * error){
        
    }];
    
}

//评论按钮响应事件
-(void)pingTouchAction:(UIButton *)sender
{
//    self.p_infoid=[NSString stringWithFormat:@"%ld",(long)sender.tag];
    [_backView removeFromSuperview];
    [[UIApplication sharedApplication].keyWindow addSubview:_bottomView];
    
    _textView.text = @"";
    _textView.tag = 0;
    
    [_textView becomeFirstResponder];
    
//    _keyboardState = NO;
    
}

//添加评论接口
-(void)addPingLunandTag:(long)tag
{
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_info_replyadd" forKey:@"method"];
    [dict setObject:_infoid forKey:@"infoid"];
    [dict setObject:USERID forKey:@"userid"];
    
    NSString *toUserStr = [NSString stringWithFormat:@"%ld",tag];
    
    if (tag > 0) {  //大于0表示
        
        [dict setObject:toUserStr forKey:@"touserid"];
    }
    
    [dict setObject:_textView.text forKey:@"scontent"];
    
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        
        [self requestForDeatilDynamic];
        
    } failure:^(NSInteger recode, NSError * error){
        
        
    }];
    
}

#pragma mark -收藏
-(void)cangAction:(UIButton *)sender
{
    [_backView removeFromSuperview];
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_info_collectionadd" forKey:@"method"];
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)sender.tag] forKey:@"infoid"];
    [dict setObject:USERID forKey:@"userid"];
    
    [Utils noIndiGet:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        
        [self shouCangAlert];
    } failure:^(NSInteger recode, NSError * error){
        
        
    }];
}

-(void)shouCangAlert
{
    control=[[UIControl alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGH)];
    control.backgroundColor=[UIColor clearColor];
    
    img=[[UIImageView alloc]initWithFrame:CGRectMake((SCREENWIDTH-120)/2, ( SCREENHEIGH-120)/2, 120, 120)];
    img.image=[UIImage imageNamed:@"shoucang_"];
    [control addSubview:img];
    
    UIWindow *window=KeyWindow;
    [window addSubview:control];
    
    [self performSelector:@selector(cancelAction) withObject:nil afterDelay:1];
    
}
-(void)cancelAction
{
    [control removeFromSuperview];
}



-(void)textViewDidBeginEditing:(UITextView *)textView{
    
    //    if([textView.text isEqualToString:@"点此输入评论"]){
    
    
    textView.textColor=[UIColor blackColor];
    //    }
    
}

-(void)textViewDidChange:(UITextView *)textView{
    
    if ([textView.text hasPrefix:@"回复"]) {
        textView.text=@"";
    }
    
    textView.textColor=[UIColor blackColor];
}

-(BOOL)textViewShouldEndEditing:(UITextView *)textView{
    
    [_textView resignFirstResponder];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    _bottomView.frame = CGRectMake(0, SCREENHEIGH-50, SCREENWIDTH, 50);
    [UIView commitAnimations];
    
    return YES;
    
}



#pragma mark -UITextViewDelegate
#pragma mark -发送评论
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if ([text isEqualToString:@"\n"]) {
        
        [_textView resignFirstResponder];
        long tag = _textView.tag;
        
        [self addPingLunandTag:tag];
        
        return NO;
    }
    return YES;
}



#pragma mark -Request
- (void)requestForDeatilDynamic{
    
    BaseModel *param = [BaseModel param];
    
    param.method = @"api_info_getreplay";
    param.infoid = _infoid;
    

    __weak typeof(self) weakSelf = self;
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dict = [[jsonObject objectForKey:@"re_data"] firstObject];
        
        if (![dict isKindOfClass:[NSDictionary class]]) {
            
            TTAlert(@"服务器发生错误");
            return;
        }
        
        weakSelf.dict = dict;
        [weakSelf.table reloadData];
        
    } failure:^(NSInteger recode, NSError *error) {
        
        
    }];
}


#pragma mark -LikeCommentViewDelegate

//点击了好用户
- (void)onclikerUser:(NSUInteger)userId{

    NSLog(@"点击了用户");
}

//点击了回复
- (void)onclikerComment:(NSString *)commentId andUserid:(NSString *)userid andTag:(int)tag andReplayid:(NSInteger)replayid{
    
    if ([userid isEqualToString:USERID]) {
        
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"删除" otherButtonTitles:nil];
        [sheet showInView:self.view];
        sheet.tag = replayid;
        return;
    }
    
    [_backView removeFromSuperview];
    [[UIApplication sharedApplication].keyWindow addSubview:_bottomView];
    
    _textView.text = [NSString stringWithFormat:@"回复%@ : ",commentId];
    
    _textView.textColor = [UIColor lightGrayColor];
    _textView.tag = [userid integerValue];
    [_textView becomeFirstResponder];
}


#pragma mark -UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    
    
    if (actionSheet.tag != 1) {  //评论
        
        if (buttonIndex == 1) {  //取消
            
        }else{  //删除回复
            
            if (actionSheet.tag == 100) {
                

                
                NSString *infoid= [NSString stringWithFormat:@"%@",[_dict objectForKey:@"infoid"]];//动态id
                
                NSString * classid =[NSString stringWithFormat:@"%@",[_dict objectForKey:@"classid"]]; //动态id
                
                NSString *studentId = @"0";
                NSString *userid = USERID; //
                
                
                NSMutableDictionary *param = [NSMutableDictionary dictionary];
                
                [param setObject:@"api_info_delete" forKey:@"Method"];
                [param setObject:infoid forKey:@"infoid"];
                [param setObject:classid forKey:@"classid"];
                [param setObject:studentId forKey:@"studentid"];
                [param setObject:userid forKey:@"userid"];
                
                [Utils get:nil parameters:param success:^(NSInteger recode, id jsonObject) {
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    //[self requestForDeatilDynamic];
                    
                } failure:^(NSInteger recode, NSError *error) {
                    
                    
                }];
                
                return;
                
            }else{
                
                NSString * tag = [NSString stringWithFormat:@"%ld",(long)actionSheet.tag];
                
                NSMutableDictionary *param = [NSMutableDictionary dictionary];
                
                [param setObject:@"api_info_replydel" forKey:@"Method"];
                [param setObject:tag forKey:@"replyid"];
                
                [Utils get:nil parameters:param success:^(NSInteger recode, id jsonObject) {
                    
                    [self requestForDeatilDynamic];
                    
                    
                } failure:^(NSInteger recode, NSError *error) {
                    
                }];
            }
        }
        
        return;
    }

    
}

@end
